package problems

import (
	"math"
)

// 1423
// https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards/
// 第一种
func MaxScore(cardPoints []int, k int) int {
	if len(cardPoints) > k*2 {
		cardPoints = append(cardPoints[:k], cardPoints[len(cardPoints)-k:]...)
	}
	size := len(cardPoints) - k
	total, min, sum := 0, 0, 0
	for k, v := range cardPoints {
		total += v
		sum += v
		if k >= size {
			sum -= cardPoints[k-size]
		} else if k == size-1 {
			min = sum
		}
		if sum < min {
			min = sum
		}
	}
	return total - min
}

// 第二种
func MaxScore2(cardPoints []int, k int) int {
	sum := 0
	for i := 0; i < k; i++ {
		sum += cardPoints[i]
	}
	max := sum
	for i := 0; i < k; i++ {
		sum += cardPoints[len(cardPoints)-1-i] - cardPoints[k-1-i]
		if sum > max {
			max = sum
		}
	}
	return max
}

// 1431
// https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies/
func KidsWithCandies(candies []int, extraCandies int) []bool {
	var res = make([]bool, len(candies))
	var max = -math.MaxInt64
	for _, v := range candies {
		if max < v {
			max = v
		}
	}
	for k, v := range candies {
		if v+extraCandies >= max {
			res[k] = true
		}
	}
	return res
}

// 1436
// https://leetcode-cn.com/problems/destination-city/
func DestCity(paths [][]string) string {
	var maps = make(map[string]string)
	for _, v := range paths {
		maps[v[0]] = v[1]
	}
	for _, v := range maps {
		if _, ok := maps[v]; !ok {
			return v
		}
	}
	return ``
}

// 1450
// https://leetcode-cn.com/problems/number-of-students-doing-homework-at-a-given-time/
func BusyStudent(startTime []int, endTime []int, queryTime int) int {
	var num = 0
	for i := 0; i < len(startTime); i++ {
		if queryTime >= startTime[i] && queryTime <= endTime[i] {
			num++
		}
	}
	return num
}

// 1460
// https://leetcode-cn.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/
func CanBeEqual(target []int, arr []int) bool {
	var maps = make(map[int]int)
	for _, v := range target {
		if _, ok := maps[v]; !ok {
			maps[v] = 0
		}
		maps[v]++
	}
	for _, v := range arr {
		if _, ok := maps[v]; !ok {
			return false
		}
		maps[v]--
		if maps[v] == 0 {
			delete(maps, v)
		}
	}
	return len(maps) == 0
}

// 1464
// https://leetcode-cn.com/problems/maximum-product-of-two-elements-in-an-array/
func MaxProduct(nums []int) int {
	var a, b = 0, 0
	for _, v := range nums {
		if v >= a {
			a, b = v, a
		} else if v >= b {
			b = v
		}
	}
	return (a - 1) * (b - 1)
}

// 1470
// https://leetcode-cn.com/problems/shuffle-the-array/
func Shuffle(nums []int, n int) []int {
	var newNums = make([]int, n*2)
	for k, v := range nums {
		if k < n {
			newNums[k*2] = v
		} else {
			newNums[(k-n)*2+1] = v
		}
	}
	return newNums
}
